package com.billy.ohos.loadingstatusview.wrapslice;

import com.billy.ohos.loading.Gloading;
import com.billy.ohos.loadingstatusview.BaseAbility;
import com.billy.ohos.loadingstatusview.util.Util;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Image;
import ohos.agp.components.StackLayout;
import ohos.agp.components.element.Element;

/**
 * demo for wrap slice
 *
 * You can wrap a BaseSlice like {@link BaseAbility}
 *
 * @author billy.qi
 * @since 19/3/21 17:23
 */
public class WrapSliceAbilitySlice extends AbilitySlice {

    private Image img;
    private Gloading.Holder holder;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        img = new Image(this);
        holder = Gloading.getDefault().wrap(img).withRetry(new Runnable() {
            @Override
            public void run() {
                loadImage(Util.getRandomImage1());
            }
        });
        loadImage(Util.getErrorImage());
        holder.getWrapper().setLayoutConfig(new StackLayout.LayoutConfig(StackLayout.LayoutConfig.MATCH_PARENT, StackLayout.LayoutConfig.MATCH_PARENT));
        super.setUIContent(holder.getWrapper());
    }

    private void loadImage(String picUrl) {
        holder.showLoading();
        getContext().getUITaskDispatcher().delayDispatch(new Runnable() {
            @Override
            public void run() {
                Glide.with(getContext())
                        .load(picUrl)
                        .listener(new RequestListener<Element>() {
                            @Override
                            public boolean onLoadFailed(GlideException exception, Object obj, Target<Element> target, boolean boo) {
                                holder.showLoadFailed();
                                return false;
                            }

                            @Override
                            public boolean onResourceReady(Element element, Object obj, Target<Element> target, DataSource dataSource, boolean boo) {
                                holder.showLoadSuccess();
                                return false;
                            }
                        })
                        .into(img);
            }
        }, 1000);
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
